package com.example.psychologicalappointmentsystem.service.impl.chatMessage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.psychologicalappointmentsystem.Entity.ChatMessageDO;
import com.example.psychologicalappointmentsystem.Entity.User;
import com.example.psychologicalappointmentsystem.Enum.ChatMessageType;
import com.example.psychologicalappointmentsystem.Enum.UserRole;
import com.example.psychologicalappointmentsystem.JpaRepository.ChatMessageRepository;
import com.example.psychologicalappointmentsystem.JpaRepository.UserRepository;
import com.example.psychologicalappointmentsystem.Object.ChatMessageVO;
import com.example.psychologicalappointmentsystem.Object.ChatSessionVO;
import com.example.psychologicalappointmentsystem.config.auth.PsyThreadLocalUtil;
import com.example.psychologicalappointmentsystem.service.ChatMessageService;
import com.google.common.collect.Lists;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * ClassName ChatMessageServiceImpl
 * Description TODO
 * Date 2025/2/14 16:32
 * Version 1.0
 */
@Service
@Slf4j
public class ChatMessageServiceImpl implements ChatMessageService {
    @Autowired
    ChatMessageRepository chatMessageRepository;

    @Autowired
    UserRepository userRepository;

    @Override
    public void saveMessage(ChatMessageVO chatMessageVO) {
        try {
            //获取当前时间
            LocalDateTime localDate = LocalDateTime.now();
            chatMessageVO.setTimestamp(localDate);

            ChatMessageDO chatMessageDO = new ChatMessageDO();
            //入库
            BeanUtil.copyProperties(chatMessageVO, chatMessageDO);
            chatMessageRepository.save(chatMessageDO);

        } catch (Exception e) {
            log.error("保存消息失败！" + e.getMessage(), e);
        }
    }

    @Override
    public void updateMessageStatus(ChatMessageVO chatMessageVO) {
        try {
            ChatMessageDO chatMessageDO = chatMessageRepository.findById(chatMessageVO.getId()).get();
            chatMessageDO.setStatus(ChatMessageType.fromDescription("READ"));
            chatMessageRepository.save(chatMessageDO);

        } catch (Exception e) {
            log.error("修改消息状态失败！" + e.getMessage(), e);
        }
    }

    @Override
    public ResponseEntity<?> chatHistory(ChatMessageVO chatMessageVO) {
        try {

            chatMessageVO.checkReceiverId();

            Long userId = PsyThreadLocalUtil.get().getUserId();

            List<ChatMessageDO> chatMessageVOList = chatMessageRepository.findOrderslast7Day(userId, chatMessageVO.getReceiverId());

            //将未读消息都改成已读消息,只修改自己作为接收方的消息
            List<ChatMessageDO> chatMessageVOReceiverList = chatMessageRepository.findOrderslast7DayReceiver(userId);
            for (ChatMessageDO chatMessageDO : chatMessageVOReceiverList) {
                chatMessageDO.setStatus(ChatMessageType.READ);
                chatMessageRepository.save(chatMessageDO);
            }

            return ResponseEntity.ok().body(chatMessageVOList);
        } catch (Exception e) {
            log.error("查询历史信息异常！" + e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("查询历史信息异常！");
        }
    }

    @Override
    public ResponseEntity<?> chatSession() {
        try {
            Long userId = PsyThreadLocalUtil.get().getUserId();
            //判断用户是否为咨询师
            User userDO = userRepository.findById(userId).get();
            List<Long> userSession = null;

            if (UserRole.VISITOR.equals(userDO.getRole())) {
                userSession = chatMessageRepository.findOrdersSession(userId);
            } else {
                userSession = chatMessageRepository.findOrdersConstentSession(userId);
            }

            List<ChatSessionVO> partnerList = Lists.newArrayList();

            Long id = 1L;
            if (!userSession.isEmpty()) {
                for (Long partnerId : userSession) {
                    ChatSessionVO chatSessionVO = new ChatSessionVO();
                    chatSessionVO.setId(id);
                    chatSessionVO.setUserId(userId);
                    chatSessionVO.setPartnerId(partnerId);
                    User userpartnerDO = userRepository.findById(partnerId).get();
                    chatSessionVO.setNickName(userpartnerDO.getNickname());

                    partnerList.add(chatSessionVO);
                    id++;
                }
            }
            return ResponseEntity.ok().body(partnerList);

        } catch (Exception e) {
            log.error("查询历史session异常！" + e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("查询历史session异常！");
        }
    }

    @Override
    public ResponseEntity<?> unread() {
        try {
            Long userId = PsyThreadLocalUtil.get().getUserId();
            int unReadTotalNum = chatMessageRepository.findOrdersUnread(userId);
            List<Object[]> unReadGroupNum = chatMessageRepository.findOrdersGroupUnread(userId);

            //总的返回
            JSONObject result = JSONUtil.createObj();
            result.append("unRead", unReadTotalNum);

            //子的返回
            List<Map<String, Object>> resultGroup = Lists.newLinkedList();
            for (Object[] object : unReadGroupNum) {
                Map<String, Object> sendMap = new HashMap<>();
                sendMap.put("senderId", object[0]);
                sendMap.put("count", object[1]);
                resultGroup.add(sendMap);
            }

            result.putOnce("data", resultGroup);

            return ResponseEntity.ok().body(result);

        } catch (Exception e) {
            log.error("获取未读消息异常！" + e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取未读消息异常！");
        }
    }
}
